{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Action1 不用任何数学库，如何求出sqrt(10)，并且精确到小数点后10位"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### ** 法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "使用 ** 计算,10的平方根为：3.1622776602\n"
     ]
    }
   ],
   "source": [
    "# **算数学库吗 →_→哈哈\n",
    "print('使用 ** 计算,10的平方根为：%.10f'%(10 ** 0.5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 二分法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "Epsilon = 1e-10\n",
    "def Sqrt10():\n",
    "    low = 3\n",
    "    high = 4\n",
    "    mid = (low + high) / 2\n",
    "    while(high-low>Epsilon):\n",
    "        if(mid*mid>10):\n",
    "            high=mid\n",
    "        else:\n",
    "            low=mid\n",
    "        mid=(low + high)/2\n",
    "    return mid"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "二分法Sqrt10函数,10的平方根为：3.1622776602\n"
     ]
    }
   ],
   "source": [
    "print('二分法Sqrt10函数,10的平方根为：%.10f'%Sqrt10())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 牛顿迭代法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "#牛顿迭代法\n",
    "# yi+1=yi - (yi2 - x) / (2yi) = yi - yi / 2 + x / (2yi) = yi / 2 + x / 2yi = (yi + x/yi) / 2\n",
    "def abs_(difference):\n",
    "    if difference < 0:\n",
    "        return -difference\n",
    "    else:\n",
    "        return difference\n",
    "def sqrt1(x):\n",
    "    y = 1.0\n",
    "    while abs_(y * y - x) > 1e-10:\n",
    "        y = (y + x/y)/2\n",
    "    return y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "牛顿迭代法,10的平方根为：3.1622776602\n"
     ]
    }
   ],
   "source": [
    "print('牛顿迭代法,10的平方根为：%.10f'%Sqrt10())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.0 64-bit ('Bi_env': venv)",
   "language": "python",
   "name": "python38064bitbienvvenvba07af95a1bb4b078aa8134bba84dff2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
